/*
 * ClassPathHacker.java
 *
 * Created on May 21, 2007, 2:59 AM
 *
 */

package tal.drivechain.system;

import java.net.URL;
import java.io.IOException;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URLClassLoader;
import java.lang.reflect.Method;

/**
 *  A Class for adding jars to the classpath at runtime. Used by {@link PluginLoader}.
 *  Copied from http://forum.java.sun.com/thread.jspa?messageID=2233419&tstart=0
 *
 */
class ClassPathHacker {
    
    private static final Class[] parameters = new Class[]{URL.class};
 
    public static void addFile(String s) throws IOException {
        File f = new File(s);
        if (!f.exists())
            throw new IOException("Classpath '" + s + "' does not exist." );
        addFile(f);
    }//end method
    
    public static void addFile(File f) throws IOException {
        addURL(f.toURI().toURL());
    }//end method
    
    
    public static void addURL(URL u) throws IOException {
        
        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class sysclass = URLClassLoader.class;
        
        try {
            Method method = sysclass.getDeclaredMethod("addURL",parameters);
            method.setAccessible(true);
            method.invoke(sysloader,new Object[]{ u });
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }//end try catch
        
    }//end method

    public static void addDir(String s) throws IOException {
        try {
            Field field = ClassLoader.class.getDeclaredField("usr_paths");
            field.setAccessible(true);
            String[] paths = (String[]) field.get(null);
            for (int i = 0; i < paths.length; i++) {
                if (s.equals(paths[i])) {
                    return;
                }
            }
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            tmp[paths.length] = s;
            field.set(null, tmp);
        } catch (IllegalAccessException e) {
            throw new IOException("Failed to get permissions to set library path");
        } catch (NoSuchFieldException e) {
            throw new IOException("Failed to get field handle to set library path");
        }
    }
}//end class


    

